#!/usr/bin/env bash

set -ex

if [ -f "khs1994-robot.enc" ];then echo -e "\n\033[32mINFO\033[0m Can't EXEC in cli folder"; exit 1; fi

# 删除原项目

print_info(){
  echo -e "\033[32mINFO\033[0m  $1\n"
}

delete(){
  ./lnmp-docker down -v > /dev/null 2>&1 || true
  print_info "删除原有项目成功"
}

docker_run(){
  docker ps -a

  sleep 5

  curl 127.0.0.1

  docker ps -a \
    && ./lnmp-docker down \
    && print_info $1
}

# 测试开发环境

_command(){

  export PATH=$PWD/bin:$PATH

  cd app/demo

  lnmp-php

  lnmp-php -v

  # lnmp-composer global config github-oauth.github.com ${GITHUB_TOKEN}
  lnmp-composer config -g --unset repos.packagist
  lnmp-composer install

  lnmp-phpunit

  cd ..

  date
  lnmp-laravel-by-composer new laravel5_5 5.5
  lnmp-laravel-by-composer new laravel6_0 6.0
  date

  lnmp-laravel new laravel
  date

  lnmp-mysql mysql -V

  lnmp-npm -v

  print_info "测试 PHPer command 完毕"
}

development(){
  print_info "开发测试开始"

  ./lnmp-docker up

  docker_run "开发境测试完毕"

  _command
}

# Swarm mode

_echo(){
  for file in "$@"
  do
    echo "# ONLY EXAMPLE" > config/nginx/$file
  done
}

swarm(){
  if ! [ -d config/nginx/ssl ];then mkdir -p config/nginx/ssl; fi

  _echo ssl/khs1994.com.key \
        ssl/khs1994.com.crt \
        ssl/khs1994.com.rsa.key \
        ssl/khs1994.com.rsa.crt \
        80.conf \
        301.conf \
        ssl.config

echo "
server {
  server_name  127.0.0.1;
  listen       80 default_server;
  root         /app/demo/public;
  index        index.html index.htm index.php;

  location / {
    try_files \$uri \$uri/ /index.php?\$query_string;
  }

  location ~ .*\.php(\/.*)*$ {
    fastcgi_pass   php7:9000;
    include        fastcgi.conf;
  }
}
" > config/nginx/khs1994.com.conf

  sed -i "s!file: /root/.ssh/id_rsa!file: ./secrets/ssh_config!g" docker-production.yml
  sed -i "s#driver: journald#driver: json-file#g" docker-production.yml

  docker node ls > /dev/null 2>&1 || docker swarm init

  docker stack rm lnmp > /dev/null 2>&1 || true

  sleep 10

  if ! [ -d app/.pcit ];then \
    git clone --depth=1 https://github.com/khs1994-php/pcit app/.pcit; \
  fi

  docker stack deploy -c docker-production.yml lnmp

  until curl 127.0.0.1; do
    docker stack ps lnmp --no-trunc
    docker ps -a
    echo "Wait nginx service start"
    sleep 5
  done

  sleep 120
  docker ps -a
  docker stack ls
  docker stack ps lnmp
  docker stack services lnmp
  docker stack rm lnmp
}

if [ ! -z "$1" ];then $1; else development; swarm; fi
